package com.fenqiyong.www;

import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.orhanobut.logger.Logger;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.utils.TbsLog;

import java.util.ArrayList;

import ren.nearby.http.base.BaseActivity;
import ren.nearby.http.view.empty.widget.ProgressWheel;

/**
 * Created by Administrator on 2019/3/12.
 */

public class WebActivity  extends BaseActivity {

    WebView x5WebView;
    ViewGroup main_fl_web;
    String mUrl;
    ProgressWheel progressWheel ;


    //文件上传
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    @Override
    public int getContentView() {
        return R.layout.web_activity;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (x5WebView != null && x5WebView.canGoBack()) {
//                x5WebView.goBack();
                if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 16) {
//                    changGoForwardButton(mWebView);
                    return true;
                }
            } else {
                startActivity(new Intent(getActivity(),MainAct.class));
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (x5WebView != null) {
            x5WebView.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent == null || x5WebView == null || intent.getData() == null) {
            return;
        }
        x5WebView.loadUrl(intent.getData().toString());
    }




    @Override
    public void onIntent() {
        super.onIntent();
        //网页中的视频，上屏幕的时候，可能出现闪烁的情况，需要如下设置：Activity在onCreate时需要设置:
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        Intent intent = getIntent();

        mUrl = intent.getStringExtra("url");


        try {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initView() {
        super.initView();

        progressWheel = findViewById(R.id.progressWheel );
                main_fl_web = findViewById(R.id.main_fl_web);


        init();
    }

    public class JavascriptCloseInterface {
        /**
         * 注意： 在Android4.2极其以上系统需要给提供js调用的方法前加入一个注视：@JavaScriptInterface;
         * 在虚拟机当中 Javascript调用Java方法会检测这个anotation，
         * 如果方法被标识@JavaScriptInterface则Javascript可以成功调用这个Java方法，否则调用不成功。
         * 注意方法名要同后台约定的相同
         */
        @JavascriptInterface
        public void over() {

            finish();
        }
    }


    public void init() {
        x5WebView = new WebView(this);


        main_fl_web.addView(x5WebView,
                new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT)
        );



        //设置webView基本信息
        x5WebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.e("shouldOverrideUrlLoading = " + url);

                return false;
            }


            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);



            }
        });
        x5WebView.addJavascriptInterface(new JavascriptCloseInterface(), "question");
        x5WebView.setWebChromeClient(new WebChromeClient() {


            @Override
            public boolean onJsConfirm(WebView webView, String s, String s1, JsResult jsResult) {
                Logger.e("onJsConfirm来了" + s);
                return super.onJsConfirm(webView, s, s1, jsResult);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Logger.e("openFileChooser 1");
                WebActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Logger.e("openFileChooser 2");
                WebActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Logger.e("openFileChooser 3");
                WebActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0

            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                Logger.e("openFileChooser 4:" + filePathCallback.toString());
                WebActivity.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }

            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                if (i == 100) {
                    progressWheel.setVisibility(View.GONE);
                }



            }


        });


        WebSettings webSetting = x5WebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setSupportZoom(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setBuiltInZoomControls(true);

        webSetting.setDisplayZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setBlockNetworkImage(false);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            webSetting.setMixedContentMode(webSetting.getMixedContentMode());
        }

        long time = System.currentTimeMillis();
        x5WebView.loadUrl(mUrl);

        //去除QQ浏览器推广广告
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                ArrayList<View> outView = new ArrayList<View>();
                getWindow().getDecorView().findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT);
                if (outView.size() > 0) {
                    outView.get(0).setVisibility(View.GONE);
                }
            }
        });
        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));
//        CookieSyncManager.createInstance(this);
//        CookieSyncManager.getInstance().sync();
    }

    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }
    }
}
